package com.baoy.cloud.xxx.sso.utils;

import com.baoy.cloud.xxx.common.utils.Digests;
import com.baoy.cloud.xxx.common.utils.Encodes;
import com.baoy.cloud.xxx.sso.config.properties.ShiroProperties;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class EncryptUtils {

    private static EncryptUtils util;

    private EncryptUtils() {
        util = this;
    }

    @Autowired
    ShiroProperties shiroProperties;


    public static byte[] generateSalt() {
        return Digests.generateSalt(util.shiroProperties.getSaltSize());
    }

    public static String entryptPassword(String plainPassword, byte[] salt) {
        String plain = Encodes.unescapeHtml(plainPassword);
        SimpleHash simpleHash = new SimpleHash(util.shiroProperties.getHashAlgorithm(),
                plain.getBytes(), salt, util.shiroProperties.getHashIterations());
        if (log.isDebugEnabled()) {
            log.debug("hashAlgorithm is {}, hashIterations is {}, salt is {}, simpleHash is {}",
                    new Object[]{util.shiroProperties.getHashAlgorithm(),
                            util.shiroProperties.getHashIterations(), salt, simpleHash.toString()});
        }
        return Encodes.encodeHex(salt) + Encodes.encodeHex(simpleHash.getBytes());
    }
}
